<template>
  <div class="home-container">
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <div class="chart-container">
          <div class="chat-title">智能投顾助手</div>
          <div class="chat-history" ref="chatHistory">
            <div
                v-for="(message, index) in messages"
                :key="index"
                :class="['message', message.type === 'user' ? 'user' : '']"
            >
              <div
                  class="message-content"
                  :class="{ 'markdown-body': message.type === 'bot' }"
                  v-html="parseMarkdown(message.content)"
              ></div>
            </div>
          </div>
          <div class="input-container">
            <el-input
                v-model="inputText"
                placeholder="请输入消息"
                @keyup.enter="sendMessageAndClear"
            />
            <el-button type="primary" @click="sendMessageAndClear">发送</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from 'axios';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';

marked.setOptions({
  highlight: function(code, lang) {
    const language = hljs.getLanguage(lang) ? lang : 'plaintext';
    return hljs.highlight(code, { language }).value;
  },
  breaks: true
});

export default {
  data() {
    return {
      inputText: '',
      messages: [],
      sessionId: null
    };
  },
  methods: {
    async sendMessageAndClear() {
      if (this.inputText.trim() === '') return;

      this.messages.push({ type: 'user', content: this.inputText });

      try {
        const response = await axios.post('http://localhost:8000/user/chat/', {
          message: this.inputText,
          session_id: this.sessionId
        });

        const assistantMessage = response.data.message;
        this.messages.push({ type: 'bot', content: assistantMessage });
        this.sessionId = response.data.session_id;
      } catch (error) {
        console.error('Error sending message:', error);
        this.messages.push({
          type: 'bot',
          content: '⚠️ 获取服务器响应失败，请稍后重试'
        });
      }

      this.inputText = '';
      this.scrollToBottom();
      this.$nextTick(() => {
        this.highlightCode();
      });
    },
    parseMarkdown(content) {
      const rawHtml = marked(content);
      return DOMPurify.sanitize(rawHtml);
    },
    highlightCode() {
      document.querySelectorAll('pre code').forEach(block => {
        hljs.highlightElement(block);
      });
    },
    scrollToBottom() {
      const chatHistory = this.$refs.chatHistory;
      if (chatHistory) {
        chatHistory.scrollTop = chatHistory.scrollHeight;
      }
    }
  }
};
</script>

<style scoped>
.home-container {
  position: relative;
  padding: 20px;
  height: 80vh;
  background-color: #f9f9f9;
  box-sizing: border-box;
}

.chart-row {
  height: 100%;
  margin: 0 !important;
}

.el-col {
  height: 100%;
}

.chart-container {
  position: absolute;
  top: 20px;
  left: 20px;
  right: 20px;
  bottom: 20px;
  background-color: #fff;
  border-radius: 12px;
  padding: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.chat-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  width: fit-content;
}

.chat-history {
  flex-grow: 1;
  overflow-y: auto;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.message {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-end;
}

.message.user {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 8px;
  background-color: #f0f0f0;
  line-height: 1.6;
  word-wrap: break-word;
}

.message-content:deep() h1 {
  font-size: 1.5em;
  margin: 0.8em 0;
}

.message-content:deep() h2 {
  font-size: 1.3em;
  margin: 0.7em 0;
}

.message-content:deep() h3 {
  font-size: 1.1em;
  margin: 0.6em 0;
}

.message-content:deep() pre {
  background-color: #f8f9fa;
  padding: 1em;
  border-radius: 6px;
  overflow-x: auto;
  margin: 1em 0;
}

.message-content:deep() code {
  font-family: 'Courier New', monospace;
  padding: 0.2em 0.4em;
  border-radius: 3px;
}

.message.user .message-content {
  background-color: #007bff;
  color: #fff;
}

.message.user .message-content:deep() pre {
  background-color: rgba(0, 0, 0, 0.25);
}

.message.user .message-content:deep() code {
  background-color: rgba(0, 0, 0, 0.25);
}

.input-container {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px 10px 0;
}

.input-container .el-input {
  flex-grow: 1;
}
</style>